package cn.maxxieyi.aichatbot.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.ContentType;
import cn.hutool.http.Header;
import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONUtil;
import cn.maxxieyi.aichatbot.dto.AiChatRequest;
import cn.maxxieyi.aichatbot.dto.AiChatResponse;
import cn.maxxieyi.aichatbot.dto.TulingRobotChatRequest;
import cn.maxxieyi.aichatbot.dto.TulingRobotChatResponse;
import cn.maxxieyi.aichatbot.exception.CommonException;
import cn.maxxieyi.aichatbot.service.AiApiService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class TulingRobotApiServiceImpl implements AiApiService {

    @Value("${ai.turing-robot.apiUrl}")
    private String apiUrl = "";

    /**
     * 文本对话接口
     *
     * @param aiChatRequest
     * @return
     */
    @Override
    public AiChatResponse chatText(AiChatRequest aiChatRequest) {
        TulingRobotChatRequest TulingRobotChatRequest = (TulingRobotChatRequest)aiChatRequest;
        log.info("TulingRobot request:"+JSON.toJSONString(TulingRobotChatRequest));
        String result = HttpRequest.post(apiUrl)
                .header(Header.CONTENT_TYPE.getValue(), ContentType.JSON.getValue())
                .body(JSON.toJSONString(TulingRobotChatRequest))
//                .timeout(10000)
                .execute().body();

        log.info("TulingRobot response:"+result);

        TulingRobotChatResponse aiChatResponse = JSONObject.parseObject(result,TulingRobotChatResponse.class);
        if(StrUtil.isNotBlank(aiChatResponse.getText())){
            aiChatResponse.setSuccess(true);
            aiChatResponse.setReplyContent(aiChatResponse.getText());
        }else{
            aiChatResponse.setSuccess(false);
        }

        return aiChatResponse;
    }

    /**
     * @param params
     * @return
     */
    @Override
    public TulingRobotChatRequest buildChatRequest(JSONObject params) {

        TulingRobotChatRequest aiChatRequest = TulingRobotChatRequest.builder()
                .key(params.getString("aiApiKey"))
                .userid(params.getString("userId")!=null?params.getString("userId"):IdUtil.objectId())
                .info(params.getString("content"))
                .build();

        return aiChatRequest;
    }
}
